<template>
  <t-modal
    title="批量导入"
    width="900px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    wrapClassName="batch-modal-container"
    destroyOnClose
    v-bind:confirmLoading="confirmLoading"
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <div class="sub-title">
          上传封样数据
          <span class="tip">
            （模版内编号请保证唯一【支持.xls，.xlsx格式】）
          </span>
          <a-button
            type="primary"
            icon="arrow-down"
            class="down-button"
            @click="handleTemplate()"
          >
            下载模版
          </a-button>
        </div>
        <a-form-model-item
          label="文件"
          prop="uploadExcel"
          :rules="{
            required: false,
            message: '请选择文件',
          }"
        >
          <bjUploadFile
            type="excel"
            :count="1"
            v-model="form.uploadExcel"
            @download="downloadFile($event)"
            @change="upLoadFileChange($event, 'uploadExcel')"
            @preview="viewFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <div class="sub-title">
          上传封样图片压缩包
          <span class="tip">
            （压缩包内图片命名请以“编号_”开头，_后面为图片的名字【支持.zip格式】）
          </span>
        </div>
        <a-form-model-item
          label="压缩包"
          prop="uploadImg"
          :rules="{
            required: false,
            message: '请选择压缩包',
          }"
        >
          <bjUploadFile
            type="zip"
            :count="1"
            v-model="form.uploadImg"
            @download="downloadFile($event)"
            @change="upLoadFileChange($event, 'uploadImg')"
            @preview="viewFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { notification } from "ant-design-vue";
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { downLoadFileByArraybuffer } from "@/utils/util";
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
import { axios } from "@/utils/request";
//预览
import previewModal from "@/pages/document/minio/previewModal";
export default {
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      confirmLoading: false,
      form: {
        uploadExcel: [],
        uploadImg: [],
      },
      rules: {},
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  methods: {
    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let { url } = row;
      downloadDfs(url);
    },
    //上传文件
    upLoadFileChange({ file, index }, domain) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[domain][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form[domain][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form[domain][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form[domain][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[domain][index], "loading", false);
        });
    },

    //下载模版
    handleTemplate() {
      axios
        .get(`/probusiness/sampleSealingManagement/downloadTemplate`, {
          apiType: "file",
          responseType: "arraybuffer",
        })
        .then((res) => {
          downLoadFileByArraybuffer(res, "封样管理【模板】");
        })
        .catch((_) => {
          this.$message.error("模版下载失败，请稍后重试！");
        });
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { form } = this;
          if (form.uploadExcel.length == 0 && form.uploadImg.length == 0) {
            return this.$message.error("请至少上传一种文件数据类型");
          }
          let formData = new FormData();
          formData.append(
            "uploadExcel",
            form.uploadExcel?.[0]?.file ?? new File([], "file")
          );
          formData.append(
            "uploadImg",
            form.uploadImg?.[0]?.file ?? new File([], "file")
          );
          this.confirmLoading = true;
          axios
            .post(`/probusiness/sampleSealingManagement/importData`, formData, {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                let { data } = res;
                let errorMsg = data.errorMsg || [];
                if (errorMsg.length != 0) {
                  let msg = errorMsg.join("");
                  notification.error({
                    message: `数据成功导入${data.sucessData}条;图片成功导入${data.sucessImg}张`,
                    description: `${msg}`,
                    duration: 4,
                  });
                } else {
                  notification.error({
                    message: `数据成功导入${data.sucessData}条;图片成功导入${data.sucessImg}张`,
                    description: `批量导入成功`,
                    duration: 4,
                  });
                }
                this.closeModal();
                this.$parent.getTableData();
              } else {
                this.$message.error(res?.message ?? "导入失败");
              }
            })
            .catch((_) => {
              this.$message.error(_?.message ?? "导入失败");
            })
            .finally((_) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    //重置表单
    resetForm() {
      this.form = {
        uploadExcel: [],
        uploadImg: [],
      };
      this.$refs.ruleForm.resetFields();
    },
    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.batch-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    box-sizing: border-box;
    padding: 14px;
    max-height: 700px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    overflow-y: auto;
    .sub-title {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      font-size: 16px;
      color: #111111;
      margin-bottom: 14px;
      .tip {
        color: #ff4d4f;
      }
      .down-button {
        float: right;
      }
    }
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        flex-shrink: 0;
        width: 120px;
        white-space: pre-wrap;
        display: flex;
        justify-content: flex-end;
        line-height: 20px;
        margin-right: 2px;
        align-items: center;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        overflow: hidden;
      }
    }
    .bj-upload-file {
      .choosed-file-warp {
        width: 100%;
      }
    }
  }
}
</style>
